package cn.elwy.rcp.kit.yssuco.views;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;

import cn.elwy.common.exception.ExceptionSupport;
import cn.elwy.common.util.AssertUtil;
import cn.elwy.common.util.io.FileUtil;
import cn.elwy.osgi.config.util.RcpPathSupport;
import cn.elwy.rcp.kit.yssuco.copy.DeployYssUco;
import cn.elwy.rcp.kit.yssuco.copy.UcoLogText;

/**
 * This sample class demonstrates how to plug-in a new workbench view. The view shows data obtained from the model. The
 * sample creates a dummy model on the fly, but a real implementation would connect to the model available either in
 * this or another plug-in (e.g. the workspace). The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model objects should be presented in the view. Each view can present the
 * same model objects using different labels and icons, if needed. Alternatively, a single label provider can be shared
 * between views in order to ensure that objects of the same type are presented in the same way everywhere.
 * <p>
 */

public class KitView extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "cn.elwy.rcp.kit.yssuco.views.KitView";
	private String fileName = "YSSUCO.json";

	private Text pathText;
	private Text msgText;
	protected boolean isOpen;

	public KitView() {
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.part.ViewPart#init(org.eclipse.ui.IViewSite)
	 */
	@Override
	public void init(IViewSite site) throws PartInitException {
		super.init(site);
	}

	/**
	 * Create contents of the view part.
	 * @param parent
	 */
	@Override
	public void createPartControl(final Composite parent) {

		SashForm sashForm = new SashForm(parent, SWT.NONE);
		SashForm leftSashForm = new SashForm(sashForm, SWT.VERTICAL);
		leftSashForm.setVisible(false);

		Group group = new Group(leftSashForm, SWT.NONE);
		group.setLayout(new GridLayout(1, false));
		leftSashForm.setWeights(new int[] { 1 });
		SashForm rightSashForm = new SashForm(sashForm, SWT.NONE);
		Composite container = new Composite(rightSashForm, SWT.NONE);
		container.setLayout(new GridLayout(3, false));
		rightSashForm.setWeights(new int[] { 1 });
		sashForm.setWeights(new int[] { 1, 3 });

		pathText = new Text(container, SWT.BORDER);
		pathText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		Button selectFileButton = new Button(container, SWT.NONE);
		selectFileButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				FileDialog fileDlg = new FileDialog(parent.getShell(), SWT.OPEN | SWT.MULTI);
				fileDlg.setFilterExtensions(new String[] { "*.json" });
				fileDlg.setFilterNames(new String[] { ".json" });
				fileDlg.setText("YSSUCO部署配置");
				String filePath = fileDlg.open();
				if (filePath != null) {
					pathText.setText(filePath);
				}
			}
		});
		selectFileButton.setText(" 浏览 ");
		Button deployButton = new Button(container, SWT.NONE);
		deployButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent event) {
				isOpen = false;
				String text = pathText.getText();
				if (AssertUtil.isNotEmpty(text)) {
					File file = new File(text);
					if (file.exists() && file.isFile()) {
						msgText.setText("");
						UcoLogText ucoLog = new UcoLogText(msgText);
						DeployYssUco dy = new DeployYssUco(ucoLog);
						try {
							ucoLog.print("开始部署");
							dy.handle(file.getAbsolutePath());
							ucoLog.print("部署成功！");
						} catch (Throwable e) {
							String message = ExceptionSupport.getMessage(e);
							ucoLog.print("部署失败：" + message);
							MessageDialog.openInformation(parent.getShell(), "错误", message);
						} finally {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
							ucoLog.print("执行时间：" + sdf.format(new Date()));
						}
					}
				}
			}
		});
		deployButton.setText(" 部署 ");

		ToolBar toolBar = new ToolBar(container, SWT.FLAT | SWT.RIGHT);

		ToolItem tltmClear = new ToolItem(toolBar, SWT.NONE);
		tltmClear.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				msgText.setText("");
				isOpen = false;
			}
		});
		tltmClear.setText("清除");

		ToolItem toolItem = new ToolItem(toolBar, SWT.NONE);
		toolItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent event) {
				String text = pathText.getText();
				if (AssertUtil.isNotEmpty(text)) {
					File file = new File(text);
					if (file.exists() && file.isFile()) {
						try {
							String content = FileUtil.readFileToString(file);
							msgText.setText(content);
							isOpen = true;
						} catch (Throwable e) {
							String message = ExceptionSupport.getMessage(e);
							MessageDialog.openInformation(parent.getShell(), "错误", message);
						}
					}
				}
			}
		});
		toolItem.setText("打开");

		ToolItem tltmNewItem = new ToolItem(toolBar, SWT.NONE);
		tltmNewItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent event) {
				if (!isOpen) {
					MessageDialog.openInformation(parent.getShell(), "错误", "请先打开文件！");
					return;
				}
				String text = pathText.getText();
				if (AssertUtil.isNotEmpty(text)) {
					File file = new File(text);
					if (file.exists() && file.isFile()) {
						try {
							String content = msgText.getText();
							FileUtil.writeFileByString(file, content, "UTF-8");
							MessageDialog.openInformation(parent.getShell(), "保存成功", content);
						} catch (Throwable e) {
							String message = ExceptionSupport.getMessage(e);
							MessageDialog.openInformation(parent.getShell(), "错误", message);
						}
					}
				}
			}
		});
		tltmNewItem.setText("保存");
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		msgText = new Text(container, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
		msgText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));

		createActions();
		initializeToolBar();
		initializeMenu();

		initView();
	}

	private void initView() {
		try {
			File workspacePath = RcpPathSupport.getInstance().getWorkspacePath();
			File file = new File(workspacePath, fileName);
			if (!file.exists()) {
				String installPath = RcpPathSupport.getInstance().getInstallPath();
				file = new File(installPath, fileName);
			}
			if (file.exists()) {
				pathText.setText(file.getAbsolutePath());
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the actions.
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar.
	 */
	private void initializeToolBar() {
		// IToolBarManager toolbarManager =
		// getViewSite().getActionBars().getToolBarManager();
	}

	/**
	 * Initialize the menu.
	 */
	private void initializeMenu() {
		// IMenuManager menuManager =
		// getViewSite().getActionBars().getMenuManager();
	}

	@Override
	public void setFocus() {
		pathText.setFocus();
	}

}
